<template>
  <div class="statistice-page">
    <div class="header">
      <span style="font-size: 20px;">任务表统计指标</span>
      <Select
        ref="taskQuarterSelect"
        element-id="taskQuarterSelect"
        transfer
        v-model="taskQuarter"
        transfer-class-name="statistice-page-select"
        clearable
        filterable
        style="width: 180px"
        class="right-btn"
      >
        <Option v-for="item in taskQuarterList" :key="item.value" :value="item.value">
          {{ item.label }}
        </Option>
      </Select>
    </div>
    <div class="content">
      <Row :gutter="16" class="code-row-bg">
        <Col :span="hasPermission('TASK_SUBMIT_STATISTICS') ? '12' : '24'">
          <Card>
            <div slot="title">
              任务状态占比
              <Tooltip placement="right" transfer max-width="1200">
                <Icon type="ios-help-circle-outline" />
                <div slot="content">
                  <div>
                    量化任务管理规则：任务执行进度=（任务截至时间（月）-任务开始时间（月））/（2025年12月-任务开始时间（月））*100%。在计划百分比±10%的范围内，为正常进行。
                  </div>
                  <br />
                  <div>已完成：实际任务执行进度=100%</div>
                  <div>正常推进：计划任务执行进度-10%&lt;=实际任务执行进度&lt;=计划任务执行进度+10%</div>
                  <div>超额推进：实际任务执行进度&gt;=计划任务执行进度+10%</div>
                  <div>延期：实际任务执行进度&lt;=计划任务执行进度-10%</div>
                  <div>未启动：未到计划的任务启动时间。任务实际进度百分比为0</div>
                  <div>其他：截止最近一次统计期未提交的、提交未审核的任务。</div>
                </div>
              </Tooltip>
            </div>
            <div slot="extra">
              <RPButton optType="reset" text="下载" @click="clickDownload('tsp')" />
            </div>
            <div style="height: 30px">
              <Select transfer v-model="trgNode" style="width: 130px" class="left-btn">
                <Option v-for="(item, index) in trgNodeList" :key="index" :value="item.value">
                  {{ item.label }}
                </Option>
              </Select>
              <span class="right-btn" style="color: #929292">任务单位：项</span>
            </div>
            <pieChart :info="chartDataList" :graphicText="chartText" />
          </Card>
        </Col>
        <Col v-if="hasPermission('TASK_SUBMIT_STATISTICS')" span="12">
          <Card>
            <div slot="title">
              提交情况
            </div>
            <div slot="extra">
              <RPButton optType="reset" text="下载" @click="clickDownload('ss')" />
            </div>
            <div style="height:310px">
              <Card style="height:30%; margin-bottom: 10px" v-for="(item, index) in progressList" :key="index">
                <template v-if="item.detailList">
                  <div style="display: flex">
                    <div class="status-title" v-for="(titleInfo, index1) in item.detailList" :key="index1">
                      {{ titleInfo.title }} ：{{ titleInfo.number }}
                    </div>
                  </div>
                </template>

                <div class="status-title" v-else>{{ item.title }} ：{{ item.detail }}</div>
                <Progress
                  :class="{
                    'zero-rate': item.rate == 0,
                    'big-than-100': item.rate > 100,
                    'mini-progress': item.rate > 0
                  }"
                  :percent="item.rate"
                  :stroke-width="20"
                  :stroke-color="item.color"
                  text-inside
                />
              </Card>
            </div>
          </Card>
        </Col>
      </Row>
      <Row v-if="hasPermission('TASK_APPROVE_STATISTICS')" :gutter="16" class="code-row-bg">
        <Col span="24">
          <Card>
            <div slot="title">
              审批情况
            </div>
            <Row :gutter="16">
              <Col span="6" v-for="(item, index) in approveSituation" :key="index">
                <Card>
                  <div class="circle-content">
                    <div class="circle-left">
                      <div class="circle-title">{{ item.title }}</div>
                      <div class="circle-detail">{{ item.sum }}</div>
                    </div>
                    <i-circle
                      class="circle-right"
                      :size="80"
                      :percent="item.rate"
                      :stroke-width="20"
                      :trail-width="20"
                      stroke-linecap="square"
                      stroke-color="#43a3fb"
                    >
                    </i-circle>
                  </div>
                  <div class="circle-line"></div>
                  <div class="circle-bottom">{{ item.detail }} {{ item.rate }}%</div>
                </Card>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>
      <Row :gutter="16" class="code-row-bg">
        <Col span="24">
          <Card>
            <div slot="extra" class="tools-container">
              <div class="tools">
                <div class="item">
                  <Select transfer v-model="trgNode2" style="width: 130px" class="left-btn">
                    <Option v-for="(item, index) in trgNodeList2" :key="index" :value="item.value">
                      {{ item.label }}
                    </Option>
                  </Select>
                </div>
                <div class="item">
                  <RPButton optType="reset" text="下载" @click="clickDownload('table')" />
                </div>
              </div>
            </div>
            <Tabs v-model="tabName">
              <TabPane label="不同举措推进情况" name="name1">
                <Table row-key="id" :columns="columns" :data="list1"></Table>
              </TabPane>
              <TabPane label="不同领域推进情况" name="name2">
                <Table row-key="id" :columns="columns2" :data="list2"></Table>
              </TabPane>
            </Tabs>
          </Card>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script>
import pieChart from './pie-chart.vue'
import sysConfigApi from '@/api/sysConfig.js'
import permission from '@/mixin/permission'
export default {
  name: 'statistice-page',
  mixins: [permission],
  components: { pieChart },
  data() {
    return {
      tabName: 'name1',
      // 统计周期
      taskQuarter: '',
      // 统计周期list
      taskQuarterList: [],
      // 业务单元
      trgNode: '',
      // 业务单元list
      trgNodeList: [],

      // 任务总数
      chartText: '', // 圆环图任务总数
      // 任务状态占比数据
      chartDataList: [],
      // 提交情况
      progressList: [],
      // 审批情况
      approveSituation: [],
      columns: [
        {
          title: '任务状态',
          key: 'status',
          tree: true
        },
        {
          title: '举措大类',
          key: 'bigCategory'
        },
        {
          title: '数量',
          key: 'count'
        },
        {
          title: '占比（总）',
          key: 'total'
        },
        {
          title: '占比（当前）',
          key: 'current'
        }
      ],
      columns2: [
        // 不同领域完成情况列表
        {
          title: '举措大类',
          key: 'bigCategory',
          tree: true
        },
        {
          title: '状态',
          key: 'status'
        },
        {
          title: '数量',
          key: 'count'
        },
        {
          title: '占比（总）',
          key: 'total'
        },
        {
          title: '占比（当前）',
          key: 'current'
        }
      ],
      // 不同举措完成情况数据&不同领域完成情况数据---业务单元
      trgNode2: '',
      // 不同举措完成情况数据&不同领域完成情况数据---业务单元list
      trgNodeList2: [],
      // 不同举措完成情况数据
      list1: [],
      // 不同领域完成情况数据
      list2: []
    }
  },
  computed: {},
  created() {
    this.init()
  },
  mounted() {
    // 处理select组件搜索后直接失去焦点后下拉选项不全只显示上次搜索结果问题
    document.getElementById('taskQuarterSelect').addEventListener('blur', () => {
      setTimeout(() => {
        this.$refs['taskQuarterSelect'].filterQueryChange = false
      }, 300)
    })
  },
  watch: {
    taskQuarter(val) {
      this.refreshData()
      this.refreshData2()
    },
    trgNode(val) {
      this.refreshData()
    },
    trgNode2(val) {
      this.refreshData2()
    }
  },
  methods: {
    _setTaskStatisticData(res) {
      let data = res.data.data || {}
      // 任务状态占比
      let plantaskDataTable = data.plantaskDataTable ? data.plantaskDataTable : []
      this.chartDataList = plantaskDataTable.filter(item => item.status != '任务总数')
      this.chartText = plantaskDataTable.filter(item => item.status == '任务总数')[0]
        ? '' + plantaskDataTable.filter(item => item.status == '任务总数')[0].sum
        : '0'

      // 提交状况
      let submitSituationTable = data.submitSituationTable ? data.submitSituationTable : []
      let submitedUnit = submitSituationTable.filter(item => item.title == '已提交单位')[0] || {}
      let submitedTask = submitSituationTable.filter(item => item.title == '已提交任务')[0] || {}
      this.progressList = [
        {
          title: '已提交单位',
          detail: submitedUnit ? submitedUnit.detail : '',
          rate: submitedUnit.rate ? submitedUnit.rate : 0,
          color: '#f2ba5d'
        },
        {
          title: '已提交任务',
          detailList: [
            {
              title: '应提交任务数',
              number: submitedTask.detail ? submitedTask.detail.split('/')[1] : ''
            },
            {
              title: '已提交任务数',
              number: submitedTask.detail ? submitedTask.detail.split('/')[0] : ''
            }
          ],
          detail: submitedTask ? submitedTask.detail : '',
          rate: submitedTask.rate ? submitedTask.rate : 0,
          color: '#41a996'
        }
      ]

      // 审批情况
      let approveSituationTable = data.approveSituationTable ? data.approveSituationTable : []
      let waitApprove = approveSituationTable.filter(item => item.title == '待审核数')[0]
      let approved = approveSituationTable.filter(item => item.title == '审核数')[0]
      let passed = approveSituationTable.filter(item => item.title == '通过数')[0]
      let rejected = approveSituationTable.filter(item => item.title == '驳回数')[0]
      let rejectedUnSubmit = approveSituationTable.filter(item => item.title == '驳回后待提交数')[0]
      this.approveSituation = [
        {
          title: '待审核数',
          detail: waitApprove ? waitApprove.detail : '',
          rate: waitApprove ? waitApprove.rate : 0,
          sum: waitApprove ? waitApprove.sum : 0
        },
        // {
        //   title: '审核数',
        //   detail: approved ? approved.detail : '',
        //   rate: approved ? approved.rate : 0,
        //   sum: approved ? approved.sum : 0,
        // },
        {
          title: '通过数',
          detail: passed ? passed.detail : '',
          rate: passed ? passed.rate : 0,
          sum: passed ? passed.sum : 0
        },
        {
          title: '驳回数',
          detail: rejected ? rejected.detail : '',
          rate: rejected ? rejected.rate : 0,
          sum: rejected ? rejected.sum : 0
        },
        {
          title: '驳回后待提交数',
          detail: rejectedUnSubmit ? rejectedUnSubmit.detail : '驳回后待提交率',
          rate: rejectedUnSubmit ? rejectedUnSubmit.rate : 0,
          sum: rejectedUnSubmit ? rejectedUnSubmit.sum : 0
        }
      ]
    },
    _setMeasureAndAreaStaticData(res) {
      let data = res.data.data || {}
      let result1 = []
      let result2 = []
      // 为了实现表格树状数据展开效果，需要给每条数据加上唯一ID
      // 不同举措完成情况
      result1 = data.diffMeasureTable || []
      result1.forEach((item, index) => {
        item.id = 100 + index + 1
        if (item.children && item.children.length > 0) {
          item.children.forEach((item2, index2) => {
            item2.id = index + 1 + '000' + index2 + 1
          })
        }
      })
      this.list1 = result1
      // 不同领域完成情况
      result2 = data.diffAreaTable || []
      result2.forEach((item, index) => {
        item.id = 200 + index + 1
        if (item.children && item.children.length > 0) {
          item.children.forEach((item2, index2) => {
            item2.id = index + 2 + '000' + index2 + 1
          })
        }
      })
      this.list2 = result2
    },
    async init() {
      let res = await this.getCycleList()
      if (res.data.code == 200) {
        let data1 = res.data.data
        this.taskQuarterList = data1
          ? data1.map(val => {
              return { label: val, value: val }
            })
          : []
        this.taskQuarter = data1.length > 0 ? data1[0] : ''
      }
      res = await this.getBusinessUnitList()
      if (res.data.code == 200) {
        let data2 = res.data.data
        this.trgNodeList = data2
          ? data2.map(val => {
              return { label: val, value: val }
            })
          : []
        this.trgNode = data2.length > 0 ? data2[0] : ''
        this.trgNodeList2 = data2
          ? data2.map(val => {
              return { label: val, value: val }
            })
          : []
        this.trgNode2 = data2.length > 0 ? data2[0] : ''
      }
      res = await this.getTaskStatisticData()
      if (res && res.data.code == 200) {
        this._setTaskStatisticData(res)
      }
      res = await this.getMeasureAndAreaStaticData()
      if (res && res.data.code == 200) {
        this._setMeasureAndAreaStaticData(res)
      }
    },
    // 查询任务状态占比、提交情况、审批情况
    async refreshData() {
      let res = await this.getTaskStatisticData()
      if (res && res.data.code == 200) {
        this._setTaskStatisticData(res)
      }
    },
    // 查询任务状态占比、提交情况、审批情况
    async refreshData2() {
      let res = await this.getMeasureAndAreaStaticData()
      if (res && res.data.code == 200) {
        this._setMeasureAndAreaStaticData(res)
      }
    },

    // 获取统计周期下拉数据
    getCycleList() {
      return sysConfigApi.getCycleList()
    },
    // 获取登录人业务单元下拉列表
    getBusinessUnitList() {
      return sysConfigApi.getBusinessUnitList()
    },
    // 查询统计表信息
    getTaskStatisticData() {
      if (!this.taskQuarter || !this.trgNode) {
        return
      }
      let param = {
        statCycle: this.taskQuarter,
        trgNode: this.trgNode
      }
      return sysConfigApi.getTaskStatisticData(param)
    },
    // 查询不同举措完成情况、不同领域完成情况
    async getMeasureAndAreaStaticData() {
      if (!this.taskQuarter || !this.trgNode2) {
        return
      }
      let param = {
        statCycle: this.taskQuarter,
        trgNode: this.trgNode2
      }
      return sysConfigApi.getMeasureAndAreaStaticData(param)
    },
    clickDownload(reportNum) {
      // statCycle：填报周期（示例：2023-1）
      // trgNode：业务单元（示例：全集团）
      // reportNum：报表编码（任务状态占比报表：tsp，提交情况：ss，不同举措完成情况：dm，不同领域完成情况：da）
      let trgNode = this.trgNode
      if (reportNum == 'table') {
        trgNode = this.trgNode2
        if (this.tabName == 'name1') {
          reportNum = 'dm'
        } else if (this.tabName == 'name2') {
          reportNum = 'da'
        }
      }
      if (reportNum == 'ss') {
        trgNode = '全集团'
      }
      let params = {
        statCycle: this.taskQuarter,
        trgNode,
        reportNum
      }
      sysConfigApi.downLoadData(params)
    }
  }
}
</script>

<style lang="less" scoped>
.statistice-page {
  height: 100%;
  .header {
    min-height: 44px;
    padding-top: 5px;
  }
  .right-btn {
    // float: right;
    position: absolute;
    right: 16px;
  }
  .content {
    height: 100%;
    .tools-container {
      .tools {
        display: flex;
        justify-content: flex-end;
        .item {
          margin: 10px 0 0 10px;
        }
      }
    }
  }
  .zero-rate /deep/.ivu-progress-inner-text {
    color: #515a6e;
  }
  .big-than-100 /deep/.ivu-progress-bg {
    width: 100% !important;
  }
  .mini-progress /deep/.ivu-progress-bg {
    min-width: 40px !important;
  }
  /deep/.ivu-card-extra {
    top: 5px;
    z-index: 1;
  }
  .status-title {
    font-size: 14px;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  /deep/.ivu-progress-bg {
    border-radius: 4px;
  }
  /deep/.ivu-progress-inner {
    border-radius: 4px;
  }
  .code-row-bg {
    margin-bottom: 16px;
  }
  .circle-content {
    position: relative;
    .circle-left {
      width: 50%;
      float: left;
      .circle-title {
        color: #929292;
        font-size: 14px;
      }
      .circle-detail {
        color: #5a5a5a;
        font-size: 30px;
      }
    }
    .circle-right {
      width: 50%;
    }
  }
  .circle-line {
    height: 1px;
    background-color: #e9e9e9;
    margin-top: 5px;
    margin-bottom: 10px;
  }
}
</style>

<style lang="less" scoped>
.statistice-page-select {
  .ivu-select-dropdown-list {
    .ivu-select-item-focus {
      background: #fff;
    }
  }
}
</style>
